#ifndef __M_THREADPOOL_H__
#define __M_THREADPOOL_H__
#include <iostream>
#include <functional>
#include <thread>
#include <future>
#include <memory>
#include <mutex>
#include <condition_variable>
#include <vector>

namespace yqx
{
    #define THREAD_NUM 5
    class ThreadPool
    {
    public:
        using ptr = std::shared_ptr<ThreadPool>;
        using Functor = std::function<void(void)>;
        ThreadPool(int thr_num = THREAD_NUM)
            : _stop(false)
        {
            for (int i = 0; i < thr_num; ++i)
            {
                _threads.emplace_back(&ThreadPool::entry, this);
            }
        }
        ~ThreadPool()
        {
            stop();
        }

        template <class F, class... Args>
        auto push(F &&func, Args &&...args) -> std::future<decltype(func(args...))>
        {
            using return_type = decltype(func(args...));
            auto tmp_func = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
            auto task = std::make_shared<std::packaged_task<return_type()>>(tmp_func);
            std::future<return_type> fu = task->get_future();
            {
                std::unique_lock<std::mutex> lock(_mtx);
                _taskpool.push_back([task]()
                                    { (*task)(); });
            }
            _cv.notify_one();
            return fu;
        }

        void stop()
        {
            if (_stop)
                return;
            _stop = true;
            _cv.notify_all();
            for (auto &thread : _threads)
            {
                thread.join();
            }
        }

    private:
        void entry()
        {
            while (!_stop)
            {
                std::vector<Functor> tmp_taskpool;
                {
                    std::unique_lock<std::mutex> lock(_mtx);
                    _cv.wait(lock, [this]()
                             { return _stop || !_taskpool.empty(); });
                    tmp_taskpool.swap(_taskpool);
                }
                for (auto &task : tmp_taskpool)
                {
                    task();
                }
            }
        }

    private:
        std::atomic<bool> _stop;
        std::vector<Functor> _taskpool;
        std::mutex _mtx;
        std::condition_variable _cv;
        std::vector<std::thread> _threads;
    };
}

#endif